import { getConfig, saveConfig } from '@/services/xyhConfig';
import { copyToClipboard } from '@/utils/format';
import { FooterToolbar, PageContainer } from '@ant-design/pro-components';
import Editor, { DiffEditor, loader } from '@monaco-editor/react';
import {
  Button,
  Checkbox,
  Collapse,
  Empty,
  Input,
  message,
  Modal,
  Space,
} from 'antd';
import { get, set } from 'lodash-es';
import * as monaco from 'monaco-editor';
import { useRef, useState } from 'react';
const { TextArea } = Input;

loader.config({ monaco });

const tabSize = 4;
const height = '500px';

const filterConfigKey = [
  {
    key: 'skill_attack_data',
    name: '技能-攻击技能',
  },
  {
    key: 'shak_skill',
    name: '技能-骨折技能',
  },
];

const DiffRender = ({ item, onExport: onPropsExport }) => {
  const diffEditorRef = useRef<any>(null);

  const handleEditorDidMount = (editor) => {
    diffEditorRef.current = editor;
    // 获取修改的编辑器实例
    const modifiedEditor = editor.getModifiedEditor();

    // 监听内容变化
    modifiedEditor.onDidChangeModelContent(() => {
      const value = modifiedEditor.getValue();
      try {
        const newValue = JSON.stringify(JSON.parse(value), null, tabSize);
        item.modified = newValue;
      } catch (error) {
        message.error('导出配置有误');
      }
    });
  };

  // 导出配置
  const onExport = () => {
    const value = diffEditorRef.current.getModifiedEditor().getValue();
    try {
      const newValue = JSON.stringify(JSON.parse(value), null, tabSize);
      onPropsExport(newValue);
    } catch (error) {
      message.error('导出配置有误');
    }
  };

  return (
    <>
      <DiffEditor
        height={height}
        language="json"
        original={item.original}
        modified={item.modified}
        // options={{
        //   tabSize,
        // }}
        onMount={handleEditorDidMount}
      />
      <div style={{ textAlign: 'right' }}>
        <Button onClick={onExport}>导出配置</Button>
      </div>
    </>
  );
};

export default () => {
  const [modalType, setModalType] = useState('');
  const [jsonValue, setJsonValue] = useState('');
  const [activeKey, setActiveKey] = useState<any>([0]);
  const [list, setList] = useState<any>([{ key: 0 }]);
  const [isAllCheck, setIsAllCheck] = useState(false);

  // 配置
  const onCover = () => {
    list.forEach((item, i) => {
      if (i === 0) {
        return;
      }
      try {
        const modifiedVal = JSON.parse(item.modified);
        const mainVal = JSON.parse(list[0].value);
        filterConfigKey.forEach((obj) => {
          // 拿到之前的配置
          const val = get(modifiedVal, obj.key);
          set(mainVal, obj.key, val);
        });
        // 漭漭配置
        if (item.roleName === '漭漭') {
          // 自动签到
          set(mainVal, 'automatic_dk', true);
          set(mainVal, 'automatic_dktime', true);
        } else {
          set(mainVal, 'automatic_dk', false);
          set(mainVal, 'automatic_dktime', false);
        }
        // 世界boss
        if (['炽热'].includes(item.roleName)) {
          set(mainVal, 'main_mob_top', 200);
          set(mainVal, 'main_skill_distance_max', 400);
        } else {
          set(mainVal, 'main_mob_top', 90);
          set(mainVal, 'main_skill_distance_max', 350);
        }
        //
        const item_buff_data = get(mainVal, 'item_buff_data'); // 保护-其他操作
        const item_buff_data1 = get(modifiedVal, 'item_buff_data');

        const new_item_buff_data = item_buff_data.map((items) => {
          if (
            ['艾利娅斯-海妮', '上京-深渊守护者', '奥亦齐-黑月公主'].includes(
              items.name,
            )
          ) {
            return item_buff_data1.find(
              (buffitem) => items.name === buffitem.name,
            );
          }
          // 家族支援

          if (
            ['贝罗斯-阿修斯', '贝斯-森生', '德鲁里吉-梅丽莎'].includes(
              items.name,
            )
          ) {
            return {
              ...items,
              sw: [
                '炽热',
                '柏屿',
                '魂刃',
                '断诀',
                '剑忆',
                '念景',
                '花续',
                '花浴',
              ].includes(item.roleName),
            };
          }
          if (items.name === '比格艾特-杰瑞') {
            return {
              ...items,
              sw: false,
            };
          }
          if (items.name === '贝罗斯-菲博') {
            return {
              ...items,
              sw: item.roleName !== '炽热',
            };
          }

          return items;
        });
        set(mainVal, 'item_buff_data', new_item_buff_data);

        if (
          [
            '炽热',
            '柏屿',
            '魂刃',
            '断诀',
            '剑忆',
            '念景',
            '花续',
            '花浴',
          ].includes(item.roleName)
        ) {
          // 脚本-补给脚本
          const autosystemscript = get(mainVal, 'autosystemscript'); // 脚本-补给脚本
          if (!autosystemscript.includes(18)) {
            set(mainVal, 'autosystemscript', [...autosystemscript, 18]);
          }
        }
        const newVal = JSON.stringify(mainVal, null, tabSize);
        item.modified = newVal;
      } catch (error) {
        console.log(error);
        message.error('覆盖失败');
      }
    });
    setList([...list]);
  };

  // 搭配配置
  const onCover2 = () => {
    list.forEach((item, i) => {
      if (i === 0) {
        return;
      }
      try {
        const modifiedVal = JSON.parse(item.modified);
        const mainVal = JSON.parse(list[0].value);
        let diysuit_item = get(mainVal, 'diysuit_item');

        diysuit_item = diysuit_item.map((items) => {
          if (items.name === '攻击套装') {
            if (item.roleName === '炽热') {
              items.data['000B0001'] = '辉黯·迅捷隐士';
            }
            if (item.roleName === '漭漭') {
              items.data['000B0001'] = '守护意志';
            }
          }
          if (items.name === '经验套装') {
            if (['柏屿', '久伴', '千迁仟'].includes(item.roleName)) {
              items.data['00010003'] = '瑞贝特的闪闪耳环';
              items.data['0001000C'] = '瑞贝特的爱心戒指';
            }
            if (['弦梦'].includes(item.roleName)) {
              items.data['00020004'] = 'LA夏日系列-仲夏夜之梦(女)上衣';
              items.data['00020005'] = 'LA夏日系列-仲夏夜之梦(女)下衣';
            }
          }
          return items;
        });

        set(modifiedVal, 'diysuit_item', diysuit_item);

        const newVal = JSON.stringify(modifiedVal, null, tabSize);
        item.modified = newVal;
      } catch (error) {
        console.log(error);
        message.error('覆盖失败');
      }
    });
    setList([...list]);
  };

  // 导入确认
  const handleOk = () => {
    let newList;
    let newValue;
    try {
      newValue = JSON.stringify(JSON.parse(jsonValue), null, tabSize);
    } catch (error) {
      message.error('导出配置有误');
      return;
    }
    if (modalType === '导入主配置') {
      list[0].value = newValue;
      newList = [...list];
      setActiveKey(0);
    } else {
      newList = [
        ...list,
        {
          original: newValue,
          modified: newValue,
        },
      ];
      setActiveKey(newList.length - 1);
    }
    setList(newList);
    setModalType('');
  };

  const onInputChange = (e) => {
    setJsonValue(e.target.value);
  };

  // 导出配置
  const onExport = (val) => {
    copyToClipboard(val);
  };

  const onAllCheck = () => {
    if (isAllCheck) {
      setList(
        list.map((item) => {
          return {
            ...item,
            checked: false,
          };
        }),
      );
      setIsAllCheck(false);
    } else {
      setList(
        list.map((item) => {
          return {
            ...item,
            checked: true,
          };
        }),
      );
      setIsAllCheck(true);
    }
  };

  const AllCheckRender = ({ item }) => {
    return (
      <div>
        <span>
          <Checkbox checked={isAllCheck} onChange={onAllCheck}>
            全选{`     ${item.value ? '主配置' : '主配置待导入'}`}
          </Checkbox>
        </span>
      </div>
    );
  };

  const items = list.map((item, i) => {
    if (i === 0) {
      if (!item.value) {
        return {
          ...item,
          label: AllCheckRender({ item }),
          children: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />,
        };
      }
      return {
        key: i,
        label: AllCheckRender({ item }),
        children: (
          <Editor
            key={item.key}
            height={height}
            defaultLanguage="json"
            value={item.value}
            onChange={(value) => {
              item.value = value;
            }}
            options={{
              tabSize,
            }}
          />
        ),
      };
    }
    return {
      key: i,
      label: (
        <div>
          <span>
            <Checkbox
              checked={item.checked}
              onChange={() => {
                list[i].checked = !list[i].checked;
                setList([...list]);
              }}
            >
              {item.roleName} - {item.path}
            </Checkbox>
          </span>
          {Boolean(item.success) && (
            <span>
              {item.success ? <span>同步成功</span> : <span>同步失败</span>}
            </span>
          )}
        </div>
      ),
      children: (
        <>
          <DiffRender item={item} onExport={onExport} />
        </>
      ),
    };
  });

  return (
    <PageContainer
      header={{
        title: '',
      }}
    >
      <Collapse
        accordion
        items={items}
        activeKey={activeKey}
        onChange={(e) => {
          setActiveKey(e);
        }}
      />
      <FooterToolbar>
        <Space style={{ marginTop: 12 }}>
          <Button
            onClick={() => {
              getConfig().then((res) => {
                console.log(res.files);
                const newList = res.files.map((item) => {
                  return {
                    ...item,
                    checked: false,
                    original: item.content,
                    modified: item.content,
                  };
                });
                const roleList = [
                  '漭漭',
                  '炽热',
                  '柏屿',
                  '虞忆',
                  '久伴',
                  '千迁仟',
                  '弦梦',
                  '魂刃',
                  '断诀',
                  '幻霜',
                  '念景',
                  '剑忆',
                  '花续',
                  '花浴',
                ];

                const newList2: any = [];
                roleList.forEach((name) => {
                  newList2.push(
                    newList.find((items) => items.roleName === name),
                  );
                });
                console.log(newList2, 'newList2');

                setList([list[0], ...newList2]);
              });
            }}
          >
            导入心月狐配置
          </Button>
          <Button onClick={() => setModalType('导入主配置')}>导入主配置</Button>
          <Button onClick={onCover}>覆盖配置</Button>
          <Button onClick={onCover2}>覆盖搭配配置</Button>
          <Button
            onClick={() => {
              const newList = list
                .slice(1)
                .filter((item) => item.checked)
                .map((item) => {
                  return {
                    path: item.path,
                    content: item.modified,
                  };
                });
              if (newList.length === 0) {
                message.error('请勾选配置');
              }

              saveConfig({
                filePaths: newList,
              }).then((res) => {
                res.results.forEach((item, i) => {
                  newList[i] = item.success;
                });

                const list2 = list.map((item) => {
                  const success = res.results.find(
                    (items) => items.path === item.path,
                  )?.success;
                  return {
                    ...item,
                    success,
                  };
                });
                setList(list2);
              });
            }}
          >
            配置同步至心月狐
          </Button>
        </Space>
      </FooterToolbar>
      <Modal
        title={modalType}
        open={!!modalType}
        onOk={handleOk}
        onCancel={() => setModalType('')}
        afterClose={() => {
          setJsonValue('');
          setModalType('');
        }}
      >
        <TextArea
          value={jsonValue}
          rows={10}
          onChange={onInputChange}
          allowClear
        />
      </Modal>
    </PageContainer>
  );
};
